package yang.VirtualMachine.chapter4;

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;

import yang.VirtualMachine.chapter4.SoftRef.User;
import yang.VirtualMachine.chapter4.SoftRefQ.UserSoftReference;

/**
 * 若引用， 一旦GC即收回
 * 可与引用队列配合使用
 * @author xinxin
 */
public class WeakRef {
	
	private static ReferenceQueue<User> queue = new ReferenceQueue<>();
	
	public static void main(String[] args) throws InterruptedException {
		User u = new User(1, "yangxx");
		WeakReference<User> userWeakRef = new WeakReference<SoftRef.User>(u, queue);
		u = null;
		System.out.println(userWeakRef.get());
		System.gc();
		TimeUnit.SECONDS.sleep(1);
		Reference<? extends User> a = queue.remove();
		System.out.println(a.get());
		// 不管当前内存是否充足，都会收回它的内存
		System.out.println("After GC:");
		System.out.println(userWeakRef.get());

	}

}
